# -*- coding: utf-8 -*-

try:
    from spider import whois_config
except ImportError:
    import whois_config

import socket


def whois(domain):
    '''get whois info from whois server'''

    try:
        tld = domain.split('.')[-1]
        server = whois_config.WHOIS_SERVER[tld]
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    except:
        return None

    fail_times = 0

    while fail_times < whois_config.MAX_RETRY_TIMES:
        try:
            s.connect((server, 43))
            break
        except socket.error:
            fail_times += 1

    if fail_times == whois_config.MAX_RETRY_TIMES:
        s.close()
        return None

    s.send('%s \r\n' % domain)
    response = []
    while 1:
        try:
            data = s.recv(1024)
        except socket.error:
            s.close()
            return None
        response.append(data)
        if data == '' or data is None:
            break
    s.close()
    whois_info = ''.join(response)
    return whois_info


if __name__ == '__main__':
    print whois("hui.lu")
